package com.ctl.utils.file;
import java.io.*;
import java.lang.String;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * <p>Title: FileLock</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2019</p>
 * <p>Company: www.ctl.com</p>
 *
 * @author ctl
 * @version 1.1
 * @date 2023-10-18 14:25
 */
public class FileLockUtil {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 获取文件锁定
        RandomAccessFile file = new RandomAccessFile("/home/ctl/lock.txt", "rw");
        FileChannel channel = file.getChannel();
        FileLock lock = null;

        try {
            // 尝试获取锁定，并设置超时时间为10秒
            lock = channel.tryLock(0L, Long.MAX_VALUE, false);
            if (lock == null) {
                System.out.println("无法获取文件锁定！");
                return;
            }

            // 执行需要锁定的操作
            System.out.println("已经获取到了文件锁定。");

            Thread.sleep(50000); // 模拟执行操作

            // 操作完成后释放锁定
            lock.release();
            System.out.println("已经释放了文件锁定。");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭Channel和RandomAccessFile对象
            channel.close();
            file.close();
        }
    }
}
